{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Supervised Fine-Tuning for Instruction Following"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Gemma](https://ai.google.dev/gemma/docs/model_card) is a groundbreaking new open model in the Gemini family of models from Google. Gemma is just as powerful as previous models but compact enough to run locally on NVIDIA RTX GPUs. Gemma is available in 2 sizes: 2B and 7B parameters. With NVIDIA NeMo, you can customize Gemma to fit your usecase and deploy an optimized model on your NVIDIA GPU.\n",
    "\n",
    "In this tutorial, we'll go over a specific kind of customization -- full parameter supervised fine-tuning for instruction following (also known as SFT). To learn how to perform Low-rank adapter (LoRA) tuning to follow a specific output format, see the [companion notebook](./lora.ipynb). For LoRA, we'll show how you can kick off a multi-GPU training job with an example script so that you can train on 8 GPUs. The exact number of GPUs needed will depend on which model you use and what kind of GPUs you use, but we recommend using 8 A100-80GB GPUs.\n",
    "\n",
    "We'll also learn how to export your custom model to TensorRT-LLM, an open-source library that accelerates and optimizes inference performance of the latest LLMs on the NVIDIA AI platform."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Supervised Fine-Tuning (SFT) is the process of fine-tuning all of a model’s parameters on supervised data of inputs and outputs. It teaches the model how to follow user specified instructions and is typically done after model pre-training. This notebook describes the steps involved in fine-tuning Gemma for instruction following. Gemma was released with a checkpoint already fine-tuned for instruction-following, but here we'll learn how we can tune our own model starting with the pre-trained checkpoint to achieve a similar outcome. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download the base model\n",
    "\n",
    "For all of our customization and deployment processes, we'll need to start off with a pre-trained version of Gemma in the `.nemo` format. You can download the base model in `.nemo` format from the NVIDIA GPU Cloud, or convert checkpoints from another framework into a `.nemo` file. You can choose to use the 2B parameter or 7B parameter Gemma models for this notebook -- the 2B model will be faster to customize, but the 7B model will be more capable. \n",
    "\n",
    "You can download either model from the NVIDIA NGC Catalog, using the NGC CLI. The instructions to install and configure the NGC CLI can be found [here](https://ngc.nvidia.com/setup/installers/cli).\n",
    "\n",
    "To download the model, execute one of the following commands, based on which model you want to use:\n",
    "\n",
    "```bash\n",
    "ngc registry model download-version \"nvidia/nemo/gemma_2b_base:1.1\"\n",
    "```\n",
    "\n",
    "or\n",
    "\n",
    "```bash\n",
    "ngc registry model download-version \"nvidia/nemo/gemma_7b_base:1.1\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting NeMo Framework\n",
    "\n",
    "NVIDIA NeMo Framework is a generative AI framework built for researchers and PyTorch developers working on large language models (LLMs), multimodal models (MM), automatic speech recognition (ASR), and text-to-speech synthesis (TTS). The primary objective of NeMo is to provide a scalable framework for researchers and developers from industry and academia to more easily implement and design new generative AI models by being able to leverage existing code and pretrained models.\n",
    "\n",
    "If you haven't already, you can pull a container that includes the version of NeMo Framework and all dependencies needed for this notebook with the following:\n",
    "\n",
    "```bash\n",
    "docker pull nvcr.io/nvidia/nemo:24.01.gemma\n",
    "```\n",
    "\n",
    "The best way to run this notebook is from within the container. You can do that by launching the container with the following command\n",
    "\n",
    "```bash\n",
    "docker run -it --rm --gpus all --ipc=host --network host -v $(pwd):/workspace nvcr.io/nvidia/nemo:24.01.gemma\n",
    "```\n",
    "\n",
    "Then, from within the container, start the jupyter server with\n",
    "\n",
    "```bash\n",
    "jupyter lab --no-browser --port=8080 --allow-root --ip 0.0.0.0\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## SFT Data Formatting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To begin, we'll need to prepare a dataset to tune our model on.\n",
    "\n",
    "This notebook uses the [Dolly dataset](https://huggingface.co/datasets/databricks/databricks-dolly-15k) as an example to demonstrate how to format your SFT data. This dataset consists of 15,000 instruction-context-response triples.\n",
    "\n",
    "First, to download the data enter the following command:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget https://huggingface.co/datasets/databricks/databricks-dolly-15k/resolve/main/databricks-dolly-15k.jsonl"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "The downloaded data, stored at `databricks-dolly-15k.jsonl`, is a `JSONL` file with each line formatted like this:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "{\n",
    "    \"instruction\": \"When did Virgin Australia start operating?\",\n",
    "    \"context\": \"Virgin Australia, the trading name of Virgin Australia Airlines Pty Ltd, is an Australian-based airline. It is the largest airline by fleet size to use the Virgin brand. It commenced services on 31 August 2000 as Virgin Blue, with two aircraft on a single route.[3] It suddenly found itself as a major airline in Australia's domestic market after the collapse of Ansett Australia in September 2001. The airline has since grown to directly serve 32 cities in Australia, from hubs in Brisbane, Melbourne and Sydney.[4]\",\n",
    "    \"response\": \"Virgin Australia commenced services on 31 August 2000 as Virgin Blue, with two aircraft on a single route.\",\n",
    "    \"category\": \"closed_qa\"\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As this example shows, there are no clear “input” and “output” fields, which are required for SFT with NeMo. To remedy this, we can do some data pre-processing. This cell converts the `instruction`, `context`, and `response` fields into `input` and `output`. It also concatenates the `instruction` and `context` fields with a `\\n\\n` separator, and randomizes the order in which they appear in the input to generate a new `JSONL` file. This generates an output file called `databricks-dolly-15k-output.jsonl`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import numpy as np\n",
    "\n",
    "path_to_data = \"databricks-dolly-15k.jsonl\"\n",
    "output_path = f\"{path_to_data.split('.')[0]}-output.jsonl\"\n",
    "with open(path_to_data, \"r\") as f, open(output_path, \"w\") as g:\n",
    "    for line in f:\n",
    "\n",
    "        # Read JSONL line in original format\n",
    "        line = json.loads(line)\n",
    "        context = line[\"context\"].strip()\n",
    "\n",
    "        # Randomize context and instruction order.\n",
    "        if context != \"\":\n",
    "            context_first = np.random.randint(0, 2) == 0\n",
    "            if context_first:\n",
    "                instruction = line[\"instruction\"].strip()\n",
    "                assert instruction != \"\"\n",
    "                input = f\"{context}\\n\\n{instruction}\"\n",
    "                output = line[\"response\"]\n",
    "            else:\n",
    "                instruction = line[\"instruction\"].strip()\n",
    "                assert instruction != \"\"\n",
    "                input = f\"{instruction}\\n\\n{context}\"\n",
    "                output = line[\"response\"]\n",
    "        else:\n",
    "            input = line[\"instruction\"]\n",
    "            output = line[\"response\"]\n",
    "\n",
    "        # Write JSONL line in new format\n",
    "        g.write(\n",
    "            json.dumps(\n",
    "                {\"input\": input, \"output\": output, \"category\": line[\"category\"]}\n",
    "            )\n",
    "            + \"\\n\"\n",
    "        )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, the dataset is a `JSONL` file with each line formatted like this: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "{\n",
    "  \"input\": \"Virgin Australia, the trading name of Virgin Australia Airlines Pty Ltd, is an Australian-based airline. It is the largest airline by fleet size to use the Virgin brand. It commenced services on 31 August 2000 as Virgin Blue, with two aircraft on a single route. It suddenly found itself as a major airline in Australia's domestic market after the collapse of Ansett Australia in September 2001. The airline has since grown to directly serve 32 cities in Australia, from hubs in Brisbane, Melbourne and Sydney.\\n\\nWhen did Virgin Australia start operating?\",\n",
    "  \"output\": \"Virgin Australia commenced services on 31 August 2000 as Virgin Blue, with two aircraft on a single route.\",\n",
    "  \"category\": \"closed_qa\"\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## SFT Training\n",
    "\n",
    "To perform the SFT Training, we'll use NVIDIA NeMo-Aligner. NeMo-Aligner is a scalable toolkit for efficient model alignment, built using the [NeMo Toolkit](https://github.com/NVIDIA/NeMo) which allows for scaling training up to 1000s of GPUs using tensor, data and pipeline parallelism for all components of alignment. Users can do end-to-end model alignment on a wide range of model sizes and take advantage of all the parallelism techniques to ensure their model alignment is done in a performant and resource efficient manner.\n",
    "\n",
    "To install NeMo Aligner, we can clone the repository and install it using `pip`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "\n",
    "git clone https://github.com/NVIDIA/NeMo-Aligner.git -b dev\n",
    "cd NeMo-Aligner\n",
    "pip install -e ."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to track and visualize your SFT training experiments, you can login to Weights and Biases. If you don't want to use wandb, make sure to set the argument `exp_manager.create_wandb_logger=False` when launching your job."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import wandb\n",
    "wandb.login()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To run SFT locally on a single node, you can use the following command. Note the `trainer.num_nodes` and `trainer.devices` arguments, which define how many nodes and how many total GPUs you want to use for training. Make sure the source model, output model, and dataset paths all match your local setup.\n",
    "\n",
    "If you'd like to perform multi-node finetuning -- for example on a slurm cluster -- you can find more information in the [NeMo-Aligner user guide](https://docs.nvidia.com/nemo-framework/user-guide/latest/modelalignment/rlhf.html#instruction-following-taught-by-supervised-fine-tuning-sft)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "%%bash\n",
    "\n",
    "cd NeMo-Aligner\n",
    "\n",
    "python examples/nlp/gpt/train_gpt_sft.py \\\n",
    "   name=gemma_dolly_finetuned \\\n",
    "   trainer.precision=bf16 \\\n",
    "   trainer.num_nodes=1 \\\n",
    "   trainer.devices=8 \\\n",
    "   trainer.sft.max_steps=-1 \\\n",
    "   trainer.sft.limit_val_batches=40 \\\n",
    "   trainer.sft.val_check_interval=1000 \\\n",
    "   model.tensor_model_parallel_size=4 \\\n",
    "   model.pipeline_model_parallel_size=1 \\\n",
    "   model.megatron_amp_O2=True \\\n",
    "   model.restore_from_path=../gemma_7b_pt.nemo \\\n",
    "   model.optim.lr=5e-6 \\\n",
    "   model.answer_only_loss=True \\\n",
    "   ++model.bias_activation_fusion=true \\\n",
    "   model.data.num_workers=0 \\\n",
    "   model.data.train_ds.micro_batch_size=1 \\\n",
    "   model.data.train_ds.global_batch_size=128 \\\n",
    "   model.data.train_ds.file_path=../databricks-dolly-15k-output.jsonl \\\n",
    "   model.data.train_ds.add_bos=True \\\n",
    "   model.data.validation_ds.micro_batch_size=1 \\\n",
    "   model.data.validation_ds.global_batch_size=128 \\\n",
    "   model.data.validation_ds.drop_last=True \\\n",
    "   model.data.validation_ds.file_path=../databricks-dolly-15k-output.jsonl \\\n",
    "   exp_manager.create_wandb_logger=True \\\n",
    "   exp_manager.explicit_log_dir=../results \\\n",
    "   exp_manager.wandb_logger_kwargs.project=sft_run \\\n",
    "   exp_manager.wandb_logger_kwargs.name=dolly_sft_run \\\n",
    "   exp_manager.checkpoint_callback_params.save_nemo_on_train_end=True \\\n",
    "   exp_manager.resume_if_exists=True \\\n",
    "   exp_manager.resume_ignore_no_checkpoint=True \\\n",
    "   exp_manager.create_checkpoint_callback=True \\\n",
    "   exp_manager.checkpoint_callback_params.monitor=validation_loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When training is finished, you should see a file called `results/checkpoints/gemma_dolly_finetuned.nemo` that contains the weights of your new, instruction-tuned model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exporting to TensorRT-LLM"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "TensorRT-LLM is an open-source library for optimizing inference performance to achieve state-of-the-art speed on NVDIA GPUs. The NeMo framework offers an easy way to compile `.nemo` models into optimized TensorRT-LLM engines which you can run locally embedded in another application, or serve to other applications using a server like Triton Inference Server."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To start with, lets create a folder where our exported model will land"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir gemma_trt_llm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To export the model, we just need to create an instance of the `TensorRTLLM` class and call the `TensorRTLLM.export()` function -- pointing the `nemo_checkpoint_path` argument to the newly fine-tuned model we trained above.\n",
    "\n",
    "This creates a couple of files in the folder we created -- an `engine` file that holds the weights and the compiled execution graph of the model, a `tokenizer.model` file which holds the tokenizer information, and `config.json` which holds some metadata about the model (along with `model.cache`, which caches some operations and makes it faster to re-compile the model in the future.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nemo.export import TensorRTLLM\n",
    "trt_llm_exporter = TensorRTLLM(model_dir=\"gemma_dolly_finetuned_trt_llm\")\n",
    "trt_llm_exporter.export(nemo_checkpoint_path=\"results/checkpoints/gemma_dolly_finetuned.nemo\", model_type=\"gemma\", n_gpus=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "With the model exported into TensorRTLLM, we can perform very fast inference"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trt_llm_exporter.forward([\"NVIDIA and Google are\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There's also a convenient function to deploy a the model as a service, backed by Triton Inference Server:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nemo.deploy import DeployPyTriton\n",
    "\n",
    "nm = DeployPyTriton(model=trt_llm_exporter, triton_model_name=\"gemma\")\n",
    "nm.deploy()\n",
    "nm.serve()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "nemo_lora",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
